<template>
  <el-image
    style="width: 130px; height: 130px; cursor: pointer"
    :src="imageUrl === '' ? UploadImage : imageUrl"
    fit="cover"
    @click="dialogTableVisible = true"
  />
  <!-- 图片合集弹窗 -->
  <div class="batch-box">
    <el-dialog
      v-model="dialogTableVisible"
      title="上传或选择图片"
      width="700"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-upload
        class="avatar-uploader"
        :action="uploadFileUrl"
        :show-file-list="false"
        :drag="props.drag"
        accept=".jpg,.png,.jpeg,.webp"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :limit="1"
        ref="uploadEle"
      >
        <el-button type="primary">上传图片</el-button>
      </el-upload>
      <!-- 展示历史图片 -->
      <div class="upload-image-all">
        <div
          class="upload-image-list"
          v-for="(item, index) in uploadImageList"
          :key="index"
          @click="selectImage(index, item.fileurl)"
        >
          <img
            src="@/assets/xuanzhong.png"
            class="select-upload-image"
            v-if="index === selectIndex"
          />
          <el-image style="width: 100%; height: 100px" :src="item.fileurl" fit="cover" />
        </div>
      </div>
      <el-text
        class="more-data"
        type="primary"
        @click="loadMore"
        v-if="uploadImageList.length >= 20"
        >{{ loadMoreText }}</el-text
      >
      <template #footer>
        <el-button @click="dialogTableVisible = false">取消</el-button>
        <el-button id="new-button" @click="okSelect" :disabled="selectIndex < 0">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import UploadImage from "@/assets/upload-image.png";
import { uploadFileUrl } from "@/api/request";
import { pictureSetApi } from "@/api/api";
import type { pictureSetRes } from "@/types/index";
import { ElMessage } from "element-plus";
// 接收父组件传来的值
const props = withDefaults(
  defineProps<{
    drag?: boolean;
    imageUrl?: string;
  }>(),
  {
    drag: false,
    imageUrl: "",
  }
);
// 监听父组件编辑商品传来的图片链接
watch(props, (newval) => {
  imageUrl.value = newval.imageUrl;
});
// 接收上传的图片链接
const imageUrl = ref("");
// 弹窗显示隐藏
const dialogTableVisible = ref(false);
// 存储图片合集
const uploadImageList = ref<pictureSetRes[]>([]);
// 弹窗出现的时候请求图片合集
watch(dialogTableVisible, async (newval) => {
  if (newval) {
    const res = await pictureSetApi({ page: 1 });
    uploadImageList.value = res.data;
  }
});
// 设置可以多次上传
const uploadEle = ref();
// 自定义事件:父组件接收子组件上传成功的图片链接
const emit = defineEmits(["uploadedUrl"]);
// 文件上传成功时的钩子
function handleAvatarSuccess(res: { data: { fileurl: string } }) {
  imageUrl.value = res.data.fileurl;
  dialogTableVisible.value = false;
  uploadEle.value.clearFiles();
  emit("uploadedUrl", res.data.fileurl);
}
// 上传文件之前的钩子
function beforeAvatarUpload(rawFile: { type: string; size: number }) {
  const imageType = ["image/jpeg", "image/jpg", "image/png", "image/webp"];
  if (!imageType.includes(rawFile.type)) {
    ElMessage({ message: "图片类型不对", duration: 1500 });
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 3) {
    ElMessage({ message: "图片文件太大", duration: 1500 });
    return false;
  }
}
// 选择哪张图片的下标
const selectIndex = ref(-1);
// 存储选中的图片链接
const selectImageUrl = ref("");
function selectImage(index: number, url: string) {
  selectIndex.value = index;
  selectImageUrl.value = url;
}
// 确定选择图片
function okSelect() {
  dialogTableVisible.value = false;
  imageUrl.value = selectImageUrl.value;
  emit("uploadedUrl", imageUrl.value);
}
// 加载更多图片
const loadMoreText = ref("加载更多");
const loadMorePage = ref(1);
async function loadMore() {
  loadMoreText.value = "加载中";
  loadMorePage.value += 1;
  const res = await pictureSetApi({ page: loadMorePage.value });
  if (res.data.length <= 0) {
    loadMoreText.value = "没有更多了";
  } else {
    uploadImageList.value = [...uploadImageList.value, ...res.data];
    loadMoreText.value = "加载更多";
  }
}
</script>

<style scoped>
.avatar-uploader {
  text-align: center;
}
.upload-image-all {
  display: flex;
  flex-wrap: wrap;
  margin-top: 50px;
}
.upload-image-list {
  position: relative;
  box-sizing: border-box;
  margin: 4px;
  width: calc(20% - 8px);
  cursor: pointer;
}
.select-upload-image {
  width: 20px;
  height: 20px;
  position: absolute;
  top: 0;
  right: 0;
  z-index: 99;
}

.batch-box /deep/ .el-dialog__body {
  overflow-y: auto;
  max-height: 300px;
}
.more-data {
  cursor: pointer;
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
